﻿using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace PLock {
	delegate void CacheInvalidatedHandler();

	class LabelCache {
		public static bool HasLabel(string label, Guid except) {
			LoadCache();

			return _cache.ContainsKey(label) && !_cache[label].Equals(except);
		}
		public static string[] GetLabels() {
			LoadCache();

			string[] arr = new string[_cache.Count];
			_cache.Keys.CopyTo(arr, 0);
			Array.Sort(arr, new CaseInsensitiveComparer());
			return arr;
		}
		public static string[] GetCaps(string label) {
			LoadCache();

			Dictionary<string, bool> d = _caps[_cache[label]];
			string[] ret = new string[d.Count];
			d.Keys.CopyTo(ret, 0);
			Array.Sort(ret);
			return ret;
		}
		public static Entry GetEntry(string label) {
			return new Entry(_cache[label]);
		}
		public static void InvalidateCache() {
			_cache = null;
			_caps = null;
			if (CacheInvalidated != null)
				CacheInvalidated();
		}

		public static event CacheInvalidatedHandler CacheInvalidated;

		private static void LoadCache() {
			if (_cache != null)
				return;

			_cache = new Dictionary<string,Guid>();
			_caps = new Dictionary<Guid,Dictionary<string,bool>>();
			foreach (string filename in Directory.GetFiles(Settings.Instance.DataFolder)) {
				string guidstr = Path.GetFileNameWithoutExtension(filename);
				Guid guid;
				try {
					guid = new Guid(guidstr);
				} catch {
					continue;
				}
				if (!_caps.ContainsKey(guid))
					_caps[guid] = new Dictionary<string, bool>();

				string ext = Path.GetExtension(filename).Substring(1);
				if (ext == "label") {
					try {
						using (StreamReader r = new StreamReader(filename, Encoding.UTF8))
							_cache[r.ReadToEnd()] = guid;
					} catch {
						continue;
					}
				} else
					_caps[guid][ext] = true;
			}
		}

		private static Dictionary<string, Guid> _cache = null;
		private static Dictionary<Guid, Dictionary<string, bool>> _caps = null;
	}
}
